package com.liuceng.zen.service;

import com.liuceng.zen.common.Result;
import com.liuceng.zen.common.utils.mapper.BeanMapper;
import com.liuceng.zen.mapper.AccountMapper;
import com.liuceng.zen.pojo.domain.Member;
import com.liuceng.zen.pojo.form.RegisterForm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;

import java.util.HashMap;
import java.util.Map;

/**
 * AccountService.java
 *
 * @author ryenlea
 */
@Service
public class AccountService {
  public static final String HASH_ALGORITHM = "SHA-1";
  public static final int HASH_INTERATIONS = 1024;
  public static final int SALT_SIZE = 8;

  private static Logger logger = LoggerFactory.getLogger(AccountService.class);

  // @Autowired
  AccountMapper accountMapper;

  public Member getMemberByUsername(String username) {
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("loginName", username);
    return accountMapper.findMember(param);
  }

  public void updateUserLoginInfo(Member user) {
    accountMapper.updateMember(user);
  }

  public Result saveUser(RegisterForm form, String captchaCode) {
    Result result = new Result();
    Errors errors = new BeanPropertyBindingResult(new RegisterForm(), "form");
    if (StringUtils.isBlank(form.getCaptcha())
        || !form.getCaptcha().toUpperCase().equals(captchaCode)) {
      // 验证码错误
      errors.rejectValue("captcha", "", "验证码错误");
      result.setErrors(errors);
      return result;
    }
    //
    Member user = BeanMapper.map(form, Member.class);
    // 检查用户名是否唯一
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("loginName", form.getLoginName());

    //
    return result;
  }

  public Member getUserById(Integer currentUserId) {
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("id", currentUserId);
    return accountMapper.findMember(param);
  }

}
